/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.rpt.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportCSV;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.modules.biz.entity.BizGoods;
import com.thinkgem.jeesite.modules.biz.rpt.entity.BizBarcodeRpt;
import com.thinkgem.jeesite.modules.biz.rpt.entity.BizBarcodeRptAll;
import com.thinkgem.jeesite.modules.biz.rpt.entity.BizGoodsRpt;
import com.thinkgem.jeesite.modules.biz.rpt.service.BizBarcodeRptService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.thinkgem.jeesite.common.web.BaseController;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 货位现存量报表
 * @author tiancheng
 * @version 2018-10-15
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/rpt/bizBarcode")
public class BizBarcodeRptController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
	@Autowired
	private BizBarcodeRptService bizBarcodeRptService;


	@RequiresPermissions(value={"biz:bizBarcodeRpt:view","biz:bizBarcodeRptAll:view"},logical= Logical.OR)
	@RequestMapping(value = {"list"})
	public String list(BizBarcodeRpt bizBarcodeRpt, HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "modules/biz/rpt/bizBarcodeRptList";
		Page<BizBarcodeRpt> page = new Page<>();
		Integer sum = 0;
		page = bizBarcodeRptService.findPage(new Page<BizBarcodeRpt>(request, response), bizBarcodeRpt);
		List<BizBarcodeRpt> bizBarcodeRptList = page.getList();
		for (BizBarcodeRpt barcodeRpt:bizBarcodeRptList) {
			sum += Integer.valueOf(barcodeRpt.getNumber());
		}
		model.addAttribute("sum", sum);
		model.addAttribute("page", page);
		return url;
	}

	 /**
	  * 不查询酱料和冷链的商品
	  * @author tiancheng
	  * @date 2018/12/3 9:00
	  * @param
	  * @return
	  */
	@RequiresPermissions(value={"biz:bizBarcodeRpt:bpList"},logical= Logical.OR)
	@RequestMapping(value = {"bpList"})
	public String bpList(BizGoodsRpt bizGoodsRpt, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BizGoodsRpt> page = new Page<>();
		Integer sum = 0;
		page = bizBarcodeRptService.findRptPage(new Page<BizGoodsRpt>(request, response), bizGoodsRpt);
		List<BizGoodsRpt> bizGoodsRptList = page.getList();
		for (BizGoodsRpt bizGoods:bizGoodsRptList) {
			sum += Integer.valueOf(bizGoods.getStockAmount());
		}
		model.addAttribute("sum", sum);
		model.addAttribute("page", page);
		return "modules/biz/rpt/bizBarcodeRptBPList";
	}

	/**
	 * 货位现存量的导出
	 * @author tiancheng
	 * @date 2018/10/10 10:15
	 * @param
	 * @return
	 */
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(BizBarcodeRpt bizBarcodeRpt, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		// 导出完毕提示的消息
		String msg = "";
		//记录日志操作
		String startOperation="开始进行货位现存量报表数据导出操作！";
		String endOperation="货位现存量报表数据导出操作结束！";
		User user = UserUtils.getUser();
		try {

			String fileNamePrefix = DateUtils.getDate("yyyyMMddHHmmss");// 导出文件名前缀

			List<String> fileNames = new ArrayList<String>(); // 存放生成的文件名称

			String exportDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId()
					+ "/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");

			String filePath = exportDir + fileNamePrefix + "/";// 导出文件子目录

			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}

			String zipFileName = fileNamePrefix + ".zip";// 压缩文件名称
			String zipFilePath = exportDir + zipFileName;// 压缩文件路径

			// 根据查询条件查询
			Page<BizBarcodeRpt> page = new Page<BizBarcodeRpt>();

			// 需要导出的数据总数目
			int dataSize = 0;
			try {
				// 获取商品列表的导出总条数
				List<BizBarcodeRpt> bizGoodsList = bizBarcodeRptService.findList(bizBarcodeRpt);
				dataSize = bizGoodsList.size();
			} catch (Exception e) {
				log.info("获取导出的数据总数目失败！失败信息：" + e.getMessage());
				LogUtils.saveLog(request, null, e, "获取导出的数据总数目失败！");
			}

			if (dataSize == 0) {
				msg = "导出失败！失败信息：导出数据为空";
				addMessage(redirectAttributes, "导出失败！失败信息：导出数据为空");
				log.info("导出失败！失败信息：导出数据为空");
				LogUtils.saveLog(request, user.getName() + "导出失败！失败信息：导出数据为空");
				return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizBarcode/list?type="+ bizBarcodeRpt.getType();
			} else {// 5000数据分一个文件
				int fileSize = StringUtils.isBlank(Global.getConfig("exportExcel.fileSize")) ? 5000
						: Integer.parseInt(Global.getConfig("exportExcel.fileSize"));
				int fileNo = dataSize / fileSize + 1;
				for (int i = 1; i <= fileNo; i++) {
					page = bizBarcodeRptService.findPage(new Page<BizBarcodeRpt>(i, fileSize), bizBarcodeRpt);
					// String fileName = fileNamePrefix + "-" +
					// String.valueOf(i) + ".xlsx";
					String fileName = fileNamePrefix + "-" + String.valueOf(i) + ".csv";
					fileNames.add(fileName);
					// 创建excel文件
					// new ExportExcel(title, SmCustomer.class, 1,
					// Integer.parseInt(exportPage)).setDataList(page.getList()).writeFile(filePath
					// + fileName);
					// 创建csv文件
					new ExportCSV(BizBarcodeRpt.class, 1).setDataList(page.getList()).writeFile(filePath + fileName);

				}

				System.out.println("需要压缩的文件所在目录：" + filePath);
				System.out.println("压缩文件所在目录：" + exportDir);
				System.out.println("压缩文件名称：" + zipFilePath);

				log.info(startOperation);
				log.info("操作人：" + UserUtils.getUser().getName());
				log.info("预计导出数据共" + dataSize + "条");

				FileUtils.zipFiles(filePath, "", zipFilePath);
				// FileUtils.downFile(new File(zipFilePath), request, response,
				// zipFileName);
				FileUtils.delFile(filePath);
				// FileUtils.delFile(zipFilePath);
				msg = "导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
						+ "<a href='" + request.getContextPath() + Global.getAdminPath()
						+ "/../static/ckfinder/ckfinder.html' style='color: #669533'>我的面板-文件管理</a>" + "”中下载！";
				addMessage(redirectAttributes,
						"导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
								+ "<a href='" + request.getContextPath() + Global.getAdminPath()
								+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！");
				log.info(endOperation);
				LogUtils.saveLog(request, user.getName() + "导出信息" + dataSize + "条");
			}
		} catch (Exception e) {
			msg = "导出失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
			log.info("导出失败！失败信息：" + e.getMessage());
			LogUtils.saveLog(request, null, e, user.getName() + "导出失败！");
		}
		return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizBarcode/list?type="+ bizBarcodeRpt.getType();
	}


	/**
	 * 其他现存量的导出
	 * @author tiancheng
	 * @date 2018/10/10 10:15
	 * @param
	 * @return
	 */
	@RequestMapping(value = "exportGoods", method = RequestMethod.POST)
	public String exportGoods(BizGoodsRpt bizGoodsRpt, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		// 导出完毕提示的消息
		String msg = "";
		//记录日志操作
		String startOperation="开始进行其他现存量报表数据导出操作！";
		String endOperation="其他现存量报表数据导出操作结束！";
		User user = UserUtils.getUser();
		try {

			String fileNamePrefix = DateUtils.getDate("yyyyMMddHHmmss");// 导出文件名前缀

			List<String> fileNames = new ArrayList<String>(); // 存放生成的文件名称

			String exportDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId()
					+ "/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");

			String filePath = exportDir + fileNamePrefix + "/";// 导出文件子目录

			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}

			String zipFileName = fileNamePrefix + ".zip";// 压缩文件名称
			String zipFilePath = exportDir + zipFileName;// 压缩文件路径

			// 根据查询条件查询
			Page<BizGoodsRpt> page = new Page<BizGoodsRpt>();

			// 需要导出的数据总数目
			int dataSize = 0;
			try {
				// 获取商品列表的导出总条数
				dataSize = bizBarcodeRptService.selectByGoodsCodeCount(bizGoodsRpt);
			} catch (Exception e) {
				log.info("获取导出的数据总数目失败！失败信息：" + e.getMessage());
				LogUtils.saveLog(request, null, e, "获取导出的数据总数目失败！");
			}

			if (dataSize == 0) {
				msg = "导出失败！失败信息：导出数据为空";
				addMessage(redirectAttributes, "导出失败！失败信息：导出数据为空");
				log.info("导出失败！失败信息：导出数据为空");
				LogUtils.saveLog(request, user.getName() + "导出失败！失败信息：导出数据为空");
				return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizBarcode/bpList";
			} else {// 5000数据分一个文件
				int fileSize = StringUtils.isBlank(Global.getConfig("exportExcel.fileSize")) ? 5000
						: Integer.parseInt(Global.getConfig("exportExcel.fileSize"));
				int fileNo = dataSize / fileSize + 1;
				for (int i = 1; i <= fileNo; i++) {
					page = bizBarcodeRptService.findRptPage(new Page<BizGoodsRpt>(i, fileSize), bizGoodsRpt);

					String fileName = fileNamePrefix + "-" + String.valueOf(i) + ".csv";
					fileNames.add(fileName);

					new ExportCSV(BizGoodsRpt.class, 1).setDataList(page.getList()).writeFile(filePath + fileName);

				}

				System.out.println("需要压缩的文件所在目录：" + filePath);
				System.out.println("压缩文件所在目录：" + exportDir);
				System.out.println("压缩文件名称：" + zipFilePath);

				log.info(startOperation);
				log.info("操作人：" + UserUtils.getUser().getName());
				log.info("预计导出数据共" + dataSize + "条");

				FileUtils.zipFiles(filePath, "", zipFilePath);
				FileUtils.delFile(filePath);
				msg = "导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
						+ "<a href='" + request.getContextPath() + Global.getAdminPath()
						+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！";
				addMessage(redirectAttributes,
						"导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
								+ "<a href='" + request.getContextPath() + Global.getAdminPath()
								+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！");
				log.info(endOperation);
				LogUtils.saveLog(request, user.getName() + "导出信息" + dataSize + "条");
			}
		} catch (Exception e) {
			msg = "导出失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
			log.info("导出失败！失败信息：" + e.getMessage());
			LogUtils.saveLog(request, null, e, user.getName() + "导出失败！");
		}
		return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizBarcode/bpList";
	}
}